package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.config.R;
import com.example.entity.Employee;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession httpSession){
        R<Employee> r=employeeService.login(employee);
        if (r.getCode()==1){//判断当前账号是否为封禁状态如果是则登陆不成功
            httpSession.setAttribute("employee",r.getData().getId());
        }
        return r;
    }

    @GetMapping("page")
    public R page(Integer page,Integer pageSize,String name){
        Page<Employee> pageInfo=new Page<>(page,pageSize);//分页，把page和pageSize传进去
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        if (name!=null){//进行判断
            queryWrapper.like(Employee::getName,name);//进行模糊查询
        }

        Page<Employee> iPage=employeeService.findPage(pageInfo,queryWrapper);
        return R.success(iPage);

    }

    @RequestMapping("logout")
    public R logut(HttpSession session){
        session.invalidate();//清空
        return R.success("退出成功");
    }

    @PostMapping
    public R addEmployee(@RequestBody Employee employee, HttpServletRequest request){


        Long id= (Long) request.getSession().getAttribute("employee");//获得当前操作人的id
        employee.setUpdateUser(id);//获取创建者的id并赋值
        employee.setCreateUser(id);//修改者的id


        employeeService.add(employee);//添加
        return R.success("成功");
    }




    @PutMapping
    public R updateEmployee(@RequestBody Employee employee,HttpSession session){
        Long id=(Long)session.getAttribute("employee");
        employee.setUpdateUser(id);//获取修改人的id
        employee.setUpdateTime(LocalDateTime.now());//获取修改时间
        employeeService.updateById(employee);//进行修改
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){

        Employee employee= employeeService.findById(id);//查询要进行修改的id
        return R.success(employee);
    }
}
